import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import { getCookie, removeCookie } from './jsCookie'
import config from './../config'
import router from './../router'
import { USERINFO } from './../constant'

// create an axios instance
const service = axios.create({
  baseURL: config.server.backServer,
  timeout: 1800000
})

function loginout() {
  removeCookie(USERINFO)
  router.push({ path: '/login' })
  loading.close()
}

let loading = ''

service.interceptors.request.use(
  (config) => {
    let userInfo = getCookie(USERINFO)

    if (userInfo && userInfo.token) config.headers['token'] = userInfo.token

    loading = ElLoading.service({
      lock: true,
      text: '加载中...'
    })

    setTimeout(() => {
      loading.close()
    }, 5000)

    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    // console.log($nuxt.$router);
    // if the custom code is not 20000, it is judged as an error.
    // console.log(loading)
    loading.close()
    if (res.code == 200) {
      return res
    } else if (res.code !== 200) {
      if (res.code == 400 && res.message == '请先登录!') {
        loginout()
      }

      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        grouping: true
      })

      return res
      // return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  (error) => {
    loading.close()
    console.log('err' + error) // for debug

    if (error == 'Error: Request failed with status code 401') {
      // loginout()
    }

    ElMessage.error(error.message || 'Error')

    return Promise.reject(error)
  }
)

function request(options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() == 'get') {
    options.params = options.data
  }
  return service(options)
}

;['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({
      url,
      data,
      method: item,
      ...options
    })
  }
})

export default request
